<template>
    <div class="base">
        <div class="left" :class="{mini: isMini}">
            <div class="base-logo" @click="isMini = !isMini"><span>{{title.userName}}</span></div>
            <BaseMenu></BaseMenu>
        </div>
        <div class="right" :class="{fixBox: isMini}">
            <div class="base-header">
                <div class="base-header-left">
                    <transition name="fade">
                        <span v-show="system" class="xx-big">{{system}}</span>
                    </transition>
                </div>
                <div class="base-header-right">
                    <span class="item cursor">
                      <span class="item-click">{{row.name}}</span>
                      <Icon type="md-arrow-dropdown" :size="23" title="组织"/>
                    </span>
                    <span class="item cursor" v-if="!isFullScreen" @click="openFullScreen">
                        <Icon :size="23" title="全屏" type="md-expand"></Icon>
                        <span>全屏</span>
                    </span>
                    <span class="item cursor" v-else  @click="closeFullScreen">
                        <Icon :size="23" title="取消全屏" type="md-contract"></Icon>
                        <span>退出全屏</span>
                    </span>
                    <span class="item item-dropdown">
                        <Avatar v-if="user.avatar" :src="preFixPath + user.avatar + '_90w'" size="large"></Avatar>
                        <Avatar v-else style="background: #fff; color: #238df2 " icon="md-person" size="large"></Avatar>
                        <span class="cursor ml">
                            <span>{{user.name}}</span>
                            <Icon type="md-arrow-dropdown"></Icon>
                        </span>
                        <div class="dropdown-content">
                            <ul>
                                <li @click="jumpUserPage">
                                    <Icon type="md-person"></Icon>
                                    账号资料
                                </li>
                                <li @click="onLogoutBtnClick">
                                    <Icon type="md-power"></Icon>
                                    退出系统
                                </li>
                            </ul>
                        </div>
                    </span>
                    <CompanySelect ref="company" :list="company" @complete="complete"></CompanySelect>
                </div>
            </div>
            <router-view></router-view>
        </div>
        <div class="bg" id="base-bg"></div>
        <transition name="fade">
            <div class="mask-loading" v-if="mask">
              <Loader :status="status"></Loader>
                <div class="mask-loading-pnl"></div>
            </div>
        </transition>
    </div>
</template>

<script>
import BaseMenu from "./BaseMenu"
import { getRandom, preFixPath } from "@/util"
import CompanySelect from '@/components/CompanySelect'
import "./bg"

export default {
  components: {
    BaseMenu,
    CompanySelect
  },
  data() {
    return {
      title: '',
      mask: false,
      status: 'pass',
      isFull: true,
      preFixPath,
      user: {
        name: "",
        avatar: ""
      },
      wifi: getRandom(10, 30),
      wifiLevel: 1,
      isFullScreen:
        document.fullscreen ||
        document.webkitIsFullScreen ||
        document.mozFullScreen ||
        false,
      isMini: !!~~localStorage.getItem("isMini"),
      system: "",
      effects: true,
      include: [],
      company: [],
      row: {}
    };
  },
  mounted() {
    // 根据浏览器大小改变伸缩左侧 （不要了！）
    this.effects = localStorage.getItem("particle") === "true";
    this.getCompany()
    this.$store.dispatch('getInfo').then(data => {
      this.title = data
    })
  },
  methods: {
    complete(row) {
      this.row.name = JSON.parse(JSON.stringify(row)).name
      if (row.id === '01') {
        this.$router.push({ name: 'company/setType/index' })
      } else {
        this.swichCompany(row)
      }
    },
    swichCompany(row) {
      this.$jsonPost('company/switchCompany', {company_id: row.id}).then(res => {
        this.$Notice.success({
          title: "切换公司成功"
        });
        window.location.reload()
      })
    },
    getCompany() {
      this.$ajaxGet('/company/companyList').then(data => {
        this.company = data.map(item => {
          return {
            name: item.company_name,
            id: item.company_id,
            switch: item.switch
          }
        })
        this.company.push({name: '创建或加入团队', id: '01'})
        this.row = JSON.parse(JSON.stringify(this.company.find(item => item.switch == 1)))
      })
      // this.company = [{ name: '中策橡胶集团', id: 0}, ]
    },  
    getUserData() {
      this.$ajaxGet("/account/info").then(data => {
        if (data) {
          this.user.avatar = data.header;
          this.user.name = data.name;
          // gtag("set", { user_id: data.member.id + "_" + data.store.id }); // 使用已登录的 user_id 来设置用户 ID。
          sessionStorage.setItem("profile", JSON.stringify(data));
        }
        setTimeout(() => (this.mask = false), 300);
      });
    },
    setMiniStyle() {
      this.isMini = true;
    },
    isIE() {
      var ua = window.navigator.userAgent;
      var msie = ua.indexOf("MSIE ");

      if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        return true;
      } else {
        return false;
      }

      return false;
    },
    onWindowSizeChange() {
      this.timer && clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (window.innerWidth < 1200) {
          this.isMini = true;
        } else if (window.innerWidth > 1200) {
          this.isMini = false;
        }
      }, 300);
    },
    onLogoutBtnClick() {
      this.$Modal.confirm({
        title: "退出登录",
        content: `确认要退出登录吗？`,
        onOk: () => {
          // this.$ajaxGet("/auth/logout").then(() => {
            this.$Notice.success({
              title: "退出成功"
            });
            localStorage.setItem('token', '')
            this.$router.replace("/login");
          // });
        }
      });
    },
    findNodeById: function(id, treeData) {
      let result;
      treeData.forEach(item => {
        if (item.id === id) {
          result = item;
        } else {
          result = (item.children || []).find(child => child.id === id);
        }
      });
      return result;
    },
    openFullScreen() {
      let body = document.body;
      if (body.requestFullscreen) {
        body.requestFullscreen();
      } else if (body.webkitRequestFullScreen) {
        // 对 Chrome 特殊处理，
        // 参数 Element.ALLOW_KEYBOARD_INPUT 使全屏状态中可以键盘输入。
        if (window.navigator.userAgent.toUpperCase().indexOf("CHROME") >= 0) {
          body.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        } else {
          // Safari 浏览器中，如果方法内有参数，则 Fullscreen 功能不可用。
          body.webkitRequestFullScreen();
        }
      } else if (body.mozRequestFullScreen) {
        body.mozRequestFullScreen();
      }
      this.isFullScreen = true;
    },
    closeFullScreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      }
      this.isFullScreen = false;
    },
    jumpUserPage() {
      this.$router.push("/home/user/edit");
    }
  },
  watch: {
    $route(to, from) {
      this.$bus.$on("avatarChange", src => (this.user.avatar = src));
      this.$bus.$on("full", isFull => (this.isFull = isFull));
      if (to.meta.keepAlive) {
        !this.include.includes(to.name) && this.include.push(to.name);
      }
      if (from.meta.keepAlive && to.meta.deepth !== 2 && !to.meta.keepAlive) { // 加!to.meta.keepAlive的原因：页码切换
        let index = this.include.indexOf(from.name)
        index !== -1 && this.include.splice(index, 1)
      }
    },
    isMini(value) {
      localStorage.setItem("isMini", value === true ? 1 : 0);
    }
  }
};
</script>

